package messages;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import db.DBManager;
import db.Message;

public class EditServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		boolean status = true;
		Message message = null;
		//	パラメータを取得
		String id = req.getParameter("id");
		
		if (id == null || id.length() == 0) {
			status = false;
		}
		else {
			//	SQLを編集
			String sql = "select * from messages where id = " + id;
			//	レコードを取得
			try {
				Connection con = DBManager.getConnection();
				Statement stm = con.createStatement();
				ResultSet rs = stm.executeQuery(sql);
				if (rs.next()) {
					message = new Message( rs );
				}
				else {
					status = false;
				}
			}
			catch (SQLException e) {
				status = false;
				e.printStackTrace();
			}
		}
		//	修正画面へ遷移する
		if (status) {
			req.setAttribute("message", message);
			RequestDispatcher dispatcher = 
					req.getRequestDispatcher("edit.jsp");
			dispatcher.forward(req, resp);
		}
		//	一覧表へ遷移する
		else {
			resp.sendRedirect("ListServlet");
		}
	}
}
